#include "stm32f10x.h"                  // Device header
#include "Timer.h"

void Timer_Init(void)
{
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);	//通用定时器2 时钟开启
	
	//此处预分频，对72M进行7200分频，计数频率为10k，计数10000，就是1s
	TIM_InternalClockConfig(TIM2);	//选择时基单元的时钟,TIM2的时基单元由内部时钟驱动，默认也是这样，添加这行，代码更完整
	TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure;
	TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1;	//指定时钟分频,先随便选个1分频
	TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up;	//向上计数
	TIM_TimeBaseInitStructure.TIM_Period = 1000 - 1;		//定时频率 = 72M/(PSC+1)/(ARR+1)
	TIM_TimeBaseInitStructure.TIM_Prescaler = 72 - 1;		//PSC和ARR都有一个数的偏差，所以减1，PSC和ARR取值范围都是0-65535
	TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0;	// 重复计数器，高级定时器才有，这里不需要用，直接给0
	TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStructure);	//配置时基单元

	
	TIM_ClearFlag(TIM2, TIM_FLAG_Update);	//防止刚上电，立马进入中断，写这一句
	//使能更新中断
	TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
	
	//NVIC 配置
	NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);	//选择分组2
	
	NVIC_InitTypeDef NVIC_InitStructure;
	NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;	//定时器2在NVIC里的通道
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
	NVIC_Init(&NVIC_InitStructure);
	
	TIM_Cmd(TIM2, ENABLE);	//启动定时器
}

/*	//中断模板
void TIM2_IRQHandler(void)
{
	if(TIM_GetITStatus(TIM2, TIM_IT_Update) == SET)	//更新中断标志位==SET
	{
		TIM_ClearITPendingBit(TIM2, TIM_IT_Update);	//清除标志位
	}
}
*/

